/*
 *
 *@author:Brett Bao,SCSE|iACT,Beihang University
 *@e-mail:baoxiwu@gmail.com
 *@last modified date:06/23/2009
 *@description:
 *用于删除文件目录的函数。
 *@notification:
 *1>需要在＊.h头文件中加入对此函数的声明;
 ＊2>@06/23/09未调试;
 *
*/
int fd_dd(char *dir)
{
	struct Entry *pentry,entry;
	int ret,offset,cluster_addr;
	int flag = 0;
	unsigned char c;
	unsigned short seed,next;
	unsigned char buf[DIR_ENTRY_SIZE];

	pentry = (struct Entry*)malloc(sizeof(struct Entry));

	/*搜寻当前目录，查找目录项*/
	ret = ScanEntry(dir,pentry,1);
	if(ret<0)
	{
		printf("no such directory!\n");
		free(pentry);
		return -1;
	}
	
	if( (ret = read(fd,buf,DIR_ENTRY_SIZE))<0)
		perror("read entry failed");

	if(curdir==NULL)
	{
		if((ret= lseek(fd,ROOTDIR_OFFSET,SEEK_SET))<0)
			perror("lseek ROOTDIR_OFFSET failed");

		offset = ROOTDIR_OFFSET;

		while(offset < (DATA_OFFSET))
		{
			ret = GetEntry(&entry);

			offset += abs(ret);
			if(ret > 0)
			{
				/*提示目录非空，然后删除*/
				if(flag == 0){
					printf("directory not empty!\n");
				}
				flag++;
				
				if(entry.subdir){
					fd_dd(entry.short_name);
				}
				else{
					fd_df(entry.short_name);
				}
			}
		}
	}

	flag = 0;

	else
	{
		cluster_addr = DATA_OFFSET + (curdir->FirstCluster-2) * CLUSTER_SIZE ;
		if((ret = lseek(fd,cluster_addr,SEEK_SET))<0)
			perror("lseek cluster_addr failed");

		offset = cluster_addr;

		while(offset<cluster_addr +CLUSTER_SIZE)
		{
			ret = GetEntry(&entry);
			offset += abs(ret);
			if(ret > 0)
			{
				/*提示目录非空，然后删除*/
				if(flag == 0){
					printf("directory not empty!\n");
				}
				flag++;

				if(entry.subdir){
					fd_dd(entry.short_name);
				}
				else{
					fd_df(entry.short_name);
				}
			}
		}
	}


	/*清除FAT表项*/
	seed = pentry->FirstCluster;
	while((next = GetFatCluster(seed))!=0xffff)
	{
		ClearFatCluster(seed);
		seed = next;

	}

	ClearFatCluster( seed );

	/*清除目录表项*/
	c=0xe5;


	if(lseek(fd,ret-0x20,SEEK_SET)<0)
		perror("lseek fd_dd failed");
	if(write(fd,&c,1)<0)
		perror("write failed");  


	if(lseek(fd,ret-0x40,SEEK_SET)<0)
		perror("lseek fd_dd failed");
	if(write(fd,&c,1)<0)
		perror("write failed");

	free(pentry);
	if(WriteFat()<0)
		exit(1);
	return 1;
}

